package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.ui.adapter.RoomFloorAdapter;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.widget.StatusLayout;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * time   : 2021/12/22
 * desc   : 房间管理界面
 */
public final class RoomManagementActivity extends AppActivity implements StatusAction {

    private static final int ADD_ROOM_CODE = 666;
    private static final int EDIT_ROOM_CODE = 777;

    private FloorBean selectedFloor;

    @Log
    public static void start(Context context) {
        Intent intent = new Intent(context, RoomManagementActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
    private StatusLayout mStatusLayout;
    private RecyclerView floorRoomRecyclerView;
    private RoomFloorAdapter mRoomFloorAdapter;
    private BottomEditDialog mBottomEditDialog;
    private int editPosition = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.room_management_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        mStatusLayout = findViewById(R.id.status_layout);
        floorRoomRecyclerView = findViewById(R.id.floor_room_recycler_view);
        floorRoomRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void onRightClick(View view) {
        gotoAddRoomActivity(null);
    }

    private void gotoAddRoomActivity(String floorSerialNo){
        Intent intent = new Intent(RoomManagementActivity.this, AddRoomActivity.class);
        intent.putExtra("floorSerialNo", floorSerialNo);
        startActivityForResult(intent, ADD_ROOM_CODE);
    }

    public void gotoEditRoomActivity(FloorBean floor, RoomBean room){
        Intent intent = new Intent(RoomManagementActivity.this, RoomSettingActivity.class);
        intent.putExtra("floorName", floor.getFloorName());
        intent.putExtra("floorType", floor.getType());
        intent.putExtra("roomName", room.getRoomName());
        intent.putExtra("roomSerialNo", room.getRoomSerialNo());
        intent.putExtra("roomSerialNo", room.getRoomSerialNo());
        intent.putExtra("floorSerialNo", room.getFloorSerialNo());
        intent.putExtra("roomType",room.getRoomTypeId());
        intent.putExtra("shareCount",room.getShareCount());
        startActivityForResult(intent, EDIT_ROOM_CODE);
    }

    @Override
    protected void initData() {
        List<FloorBean> floors = LLFloorDBManager.getInstance(this).getAllDetail();
        if(floors.size() == 0 || (floors.size() == 1 && floors.get(0).getType() == 1 && (floors.get(0).getRooms() == null || floors.get(0).getRooms().size() == 0))){
            showEmpty();
        }else{
            showComplete();
            if(mRoomFloorAdapter == null){
                mRoomFloorAdapter = new RoomFloorAdapter(this);
                mRoomFloorAdapter.setOnChildClickListener(R.id.btn_more, new BaseAdapter.OnChildClickListener() {
                    @Override
                    public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                        editPosition = position;
                        showEditFloorDialog(childView);
                    }
                });
                mRoomFloorAdapter.setOnChildClickListener(R.id.btn_add_room, new BaseAdapter.OnChildClickListener() {
                    @Override
                    public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                        gotoAddRoomActivity(mRoomFloorAdapter.getData().get(position).getFloorSerialNo());
                    }
                });
                floorRoomRecyclerView.setAdapter(mRoomFloorAdapter);
            }
            mRoomFloorAdapter.setData(floors);
        }
    }

    public void showEmpty(){
        showEmpty(R.attr.img_emptystate_noroom, R.string.no_set_room, R.string.add, new StatusLayout.OnBtnClickListener() {
            @Override
            public void onClick(StatusLayout layout) {
                gotoAddRoomActivity(null);
            }
        });
    }

    private OptionDialog optionDialog;
    private void showEditFloorDialog(View atView) {
        if (optionDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
            options.add(new OptionDialog.Option(R.attr.icon_navigationbar_edit_black, "修改名称"));
            options.add(new OptionDialog.Option(R.attr.icon_navigationbar_edit_black, "房间排序"));
            options.add(new OptionDialog.Option(R.attr.icon_me_house_delete, "删除楼层", AppApplication.getInstance().getThemeColor(R.attr.secondaryColor1)));
            optionDialog = new OptionDialog(getContext())
                    .setOptions(options);
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(getResources().getDimensionPixelSize(R.dimen.dp_6))
                    .asCustom(optionDialog);
        }
        optionDialog.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                optionDialog.dismiss();
                switch (position){
                    case 0:
                        selectedFloor = (FloorBean) atView.getTag();
                        showBottomEditDialog(selectedFloor.getFloorName());
                        break;
                    case 1:
                        selectedFloor = (FloorBean) atView.getTag();
                        Intent intent = new Intent(getContext(),RoomSrotActivity.class);
                        intent.putExtra("floorSerialNo",selectedFloor.getFloorSerialNo());
                        intent.putExtra("floorName",selectedFloor.getFloorName());
                        startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                            @Override
                            public void onActivityResult(int resultCode, Intent data) {
                                if (resultCode == RESULT_OK) {
                                    initData();
                                }
                            }
                        });
                        break;
                    case 2:
                        selectedFloor = (FloorBean) atView.getTag();
                        if(selectedFloor.getRooms() != null && selectedFloor.getRooms().size() > 0){
                            showConfirmHintDialog(R.string.floor_has_room_delete_hint);
                        }else{
                            showConfirmCancelHintDialog(getString(R.string.delete_floor_hint, selectedFloor.getFloorName()));
                        }
                        break;
                }
            }
        });
        optionDialog.popupInfo.atView = atView;
        optionDialog.show();
    }

    private void showBottomEditDialog(String oldText) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String newText = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(newText)){
                        toast(R.string.please_enter_floor_name);
                        return;
                    }
                    Map<String, Object> data = new HashMap<>();
                    data.put("floorSerialNo", selectedFloor.getFloorSerialNo());
                    data.put("newName", newText);
                    LLHttpManager.editFloorName(RoomManagementActivity.this, data, new HttpCallback<HttpData<Void>>(RoomManagementActivity.this){
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            super.onSucceed(result);
                            selectedFloor.setFloorName(newText);
                            LLFloorDBManager.getInstance(RoomManagementActivity.this).put(selectedFloor);
                            mRoomFloorAdapter.notifyItemChanged(editPosition);
                            EventBus.getDefault().post(new RefreshFloorRoomEvent());
                            toast(R.string.reset_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.floor_name));
        mBottomEditDialog.setText(oldText);
        mBottomEditDialog.setMaxLength(Constants.FLOOR_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;
    private void showConfirmHintDialog(int res){
        if(mConfirmHintDialog == null){
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity());
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setContent(res);
        mConfirmHintDialog.show();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showConfirmCancelHintDialog(String text){
        if(mConfirmCancelHintDialog == null){
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
            mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    mConfirmCancelHintDialogBuilder.dismiss();
                }

                @Override
                public void onRightClick(BaseDialog dialog) {
                    mConfirmCancelHintDialogBuilder.dismiss();
                    Map<String, Object> data = new HashMap<>();
                    data.put("floorSerialNo", selectedFloor.getFloorSerialNo());
                    LLHttpManager.deleteFloor(RoomManagementActivity.this, data, new HttpCallback<HttpData<Void>>(RoomManagementActivity.this){
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            super.onSucceed(result);
                            mRoomFloorAdapter.getData().remove(selectedFloor);
                            LLFloorDBManager.getInstance(RoomManagementActivity.this).remove(selectedFloor);
                            mRoomFloorAdapter.notifyItemRemoved(editPosition);
                            if(mRoomFloorAdapter.getData().size() == 0){
                                showEmpty();
                            }
                            EventBus.getDefault().post(new RefreshFloorRoomEvent());
                            toast(R.string.delete_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }
            });
        }
        mConfirmCancelHintDialogBuilder.setContent(text);
        mConfirmCancelHintDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
        if(resultCode != RESULT_OK){
            return;
        }
        switch (requestCode){
            case ADD_ROOM_CODE:
            case EDIT_ROOM_CODE:
                initData();
                break;
        }
    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }
}